<?php
declare (strict_types=1);

namespace app\api\middleware;

use app\common\model\VillageBusiness;
use think\Response;
use think\facade\Cache;
use app\common\model\User;
use app\common\controller\Config;
use think\exception\HttpResponseException;

class VerifyVillageBusiness
{

    public function handle($request, \Closure $next)
    {

        $system = Cache::get('system');
        if (!$system) {
            $system = Config::lists();
            Cache::set('system', $system);
        }
        if ($system['web_site_close'] != 1) {
            $this->friendlyError($request, $system['close_msg'], 'public/close', 'view');
        }

//        if ($request->isPost()) {
//            $result = $this->verifyFrequent($request);
//            if (!$result) exit();
//        }

        $result = $this->verifyToken($request);
        if ($result['code'] !== 1) {
            $this->friendlyError($result['code'], $result['msg']);
        }
        $request->user = $result['result'];
        $request->village_business = $result['village_business'];
        $request->system = $system;

        return $next($request);

    }

    protected function verifyToken($request)
    {
        $token = $request->header('token');
        if (!$token) return ['code' => 201, 'msg' => '请登录'];
        $user = User::where('token', $token)->find();
        if (empty($user)) return ['code' => 202, 'msg' => '登录已过期'];
        if ($user->is_locking) return ['code' => 202, 'msg' => '账号已锁定'];
        if (!$user->village_business_id) return ['code' => -1, 'msg' => '您不是商家'];
        $village_business = VillageBusiness::where('id', $user->village_business_id)->find();
        if (empty($user)) return ['code' => -1, 'msg' => '您不是商家'];
        return ['code' => 1, 'result' => $user, 'village_business' => $village_business];
    }

//    protected function verifyFrequent($request)
//    {
//        $array = json_encode(['ip' => $request->ip(), 'action' => $request->action()]);
//        if (Cache::get($array)) {
//            return false;
//        }
//        Cache::set($array, 1, 1);
//
//        return true;
//    }


    public function friendlyError($code, $message, $url = '', $type = '')
    {
        $result = [
            'code' => $code,
            'msg'  => $message,
        ];
        $response = Response::create($result, 'json');
        throw new HttpResponseException($response);
    }


}
